package wetalk.software.bupt.com.wetalk.view.activity;

/**
 * Created by whc07 on 2018/1/7.
 */
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.po.Group;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.widget.ClearEditText;

import static android.content.ContentValues.TAG;


public class ChangeGroupNameActivity extends BaseActivity {
    private TextView mGroupName;
    private RelativeLayout rvImgBack;
    private RelativeLayout rvImgUpdateGroupName;
    private IntentFilter intentFilter;
    private Intent intent;
    private ClearEditText mNewGroupName;//显示手机号
    private Group group;
    private String data;
    private String newName;

    private AndroidClientService.SendBinder sendBinder;
    private ChangeGroupNameReceiver changeGroupNameReceiver;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_changegroupname);
        initTitle();
        initModifyGroupNameBC();
        mGroupName = (TextView) findViewById(R.id.tv_original_groupname);
        intent = getIntent();
        data = intent.getStringExtra("extra_groupname");
        mGroupName.setText("原群名称："+data);
        Toast.makeText(ChangeGroupNameActivity.this,data,Toast.LENGTH_LONG).show();
        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);


    }
    //ChatUser currentUser  = UserManager.getInstance(ChangeGroupNameActivity.this).getCurrentUser();

    /*初始化修改密界面抬头*/
    private void initTitle() {
        rvImgBack = (RelativeLayout) findViewById(R.id.rv_img_back);

        //点击左侧布局事件
        rvImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //中间文字“修改手机号”
        TextView txtMiddle = (TextView) findViewById(R.id.txt_title);
        txtMiddle.setText("更改群名称");


        //点击右侧确定修改群组名
        rvImgUpdateGroupName = (RelativeLayout) findViewById(R.id.rv_img_right);
        mNewGroupName = (ClearEditText) findViewById(R.id.et_update_groupname);
        rvImgUpdateGroupName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String groupname = mNewGroupName.getText().toString();
                if (groupname.equals("")) {
                    Toast.makeText(ChangeGroupNameActivity.this, "不可为空", Toast.LENGTH_SHORT).show();
                }else if(groupname.equals(data)){
                    Toast.makeText(ChangeGroupNameActivity.this, "不可与当前群名重复", Toast.LENGTH_SHORT).show();
                }else {
                    group= WeTalkDB.create(ChangeGroupNameActivity.this).queryGroupByName(data);
                    changeGroupName(group.getGroup_id(),groupname,new PushListener(){
                        @Override
                        public void onSuccess() {
                            Toast.makeText(ChangeGroupNameActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(int var1, String var2) {
                            Toast.makeText(ChangeGroupNameActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                        }
                            }
                    );

                    //finish();
                }

            }
        });
    }

    private void changeGroupName(String id,String name, final PushListener pushCallback)  {
        final String targetId = "sys_group";
        final String userId= UserManager.getInstance(ChangeGroupNameActivity.this).getCurrentUser().getUserID();
        final JSONObject json=new JSONObject();
        String[]m = id.split("_");
        try {
            json.put("gid",m[0]);
            json.put("gname",name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"modifyGroupName",bs);

                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();

    }

    //注册广播接收器
    private void initModifyGroupNameBC(){
        //接收广播
        intentFilter=new IntentFilter(WeTalkConfig.BROADCAST_CHANGE_GROUP_NAME);
        changeGroupNameReceiver=new ChangeGroupNameReceiver();
        registerReceiver(changeGroupNameReceiver,intentFilter);

    }

    class ChangeGroupNameReceiver extends BroadcastReceiver {
        private Group newgroup;

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(ChangeGroupNameActivity.this, "收到修改群组信息", Toast.LENGTH_SHORT).show();
            String result=null;
            String content=intent.getStringExtra("result");
            try {
                JSONObject json=new JSONObject(content);
                result=json.getString("gid")+json.getString("gname");
                    Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();

                    newgroup=WeTalkDB.create(ChangeGroupNameActivity.this).queryGroupByID(json.getString("gid")+"_g");
                    newName = json.getString("gname");
                    newgroup.setGroup_name(newName);
                    WeTalkDB.create(ChangeGroupNameActivity.this).modifyGroupInfo(newgroup);

                Log.i(TAG, "get message: "+result);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            //abortBroadcast();
                Intent intent1=new Intent(ChangeGroupNameActivity.this,GroupSettingActivity.class);
                intent1.putExtra("groupname",newName);
                startActivity(intent1);
            Toast.makeText(ChangeGroupNameActivity.this, "修改完成", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(changeGroupNameReceiver);
        unbindService(connection);
    }
}
